﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using AbbrWordWikiDB;

namespace AbbrWordWiki
{
    public partial class EditWord : PhoneApplicationPage
    {
        private string _newWord;
        private string _fullWord;

        public EditWord()
        {
            InitializeComponent();
        }

        // When page is navigated to set data context to selected item in list
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (DataContext == null)
                DataContext = App.ViewModel;

            if (NavigationContext.QueryString.TryGetValue("newWord", out _newWord))
            {
                this.WordTextBox.Text = _newWord.ToUpper();
            }
            if (NavigationContext.QueryString.TryGetValue("fullWord", out _fullWord))
            {
                this.FullWordTextBox.Text = _fullWord;
                foreach (t_AbbrWordWiki abbrWord in App.ViewModel.AbbrWordsViewData)
                {
                    if (abbrWord.FullWord.ToLower().StartsWith(_fullWord.ToLower()))
                    {
                        this.WordTextBox.Text = abbrWord.Word;
                        this.FullWordTextBox.Text = abbrWord.FullWord;
                        this.DescriptionTextBox.Text = abbrWord.Description;
                    }
                }
            }
        }

        private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            t_AbbrWordWiki word = new t_AbbrWordWiki();
            word.Word = this.WordTextBox.Text;
            word.FullWord = this.FullWordTextBox.Text;
            word.Description = this.DescriptionTextBox.Text;

            MainViewModel dataContext = this.DataContext as MainViewModel;

            if (string.IsNullOrEmpty(_fullWord))
                dataContext.CreateNewWord(word);
            else
                dataContext.UpdateWord(word);

            // Navigate to the new page
            NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedWord=" + word.FullWord, UriKind.Relative));
        }

        private void DescriptionTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
    }
}